var fs = require("fs"), path = require("path")
var workdir = path.join(__dirname, "../");
var spawn = require("child_process").spawn;
var SYNC_INTERVAL = 30 * 1000
var async = require("async")
function getExecuter(cmd, args, cwd) {
    return function (callback) {
        var child = spawn(cmd, args, cwd);;
        child.on('error', function (err) {
            calback(null, err.stack);
        })
        child.stderr.on('data', function(chunk){
            console.log(chunk.toString())
        })
        child.stdout.on('data', function (chunk) {
            console.log(chunk.toString())
        })
        child.on('exit', function (code) {
            if (code == 0)
                callback(null, 0)
            else
                callback(null, code);
        })
    }
}

/**
 * git 同步
 */
function sync() {
    var modules = JSON.parse(fs.readFileSync("./modules.json"));
    var executes = [];
    for (var i = 0; i < modules.length; i++) {
        var mod = modules[i];
        var mpath = path.join(workdir, mod.path);

        if (fs.existsSync(mpath)) {
            console.log("prepare pull", mpath)
            executes.push(getExecuter("git", ['pull'], { cwd: mpath }))

        } else {
            console.log("prepare clone ", mod.url, "to", mpath);
            executes.push(getExecuter("git", ['clone', mod.url, mod.path], { cwd: workdir }))
        }
    }
    if (process.platform == "linux")
        executes.push(getExecuter("node", ['pm2inform'], { cwd: __dirname }))
    async.parallel(executes, function (err, result) {

    })
}

sync();
setInterval(sync, SYNC_INTERVAL);